<?php
/**
 * Manual Test Script for SixShop Maker Bundle
 * 
 * This script performs comprehensive tests of all functionality
 * Run: php tests/manual_test.php
 */

// Autoload classes
if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
    require __DIR__ . '/../vendor/autoload.php';
} elseif (file_exists(__DIR__ . '/../../../../autoload.php')) {
    require __DIR__ . '/../../../../autoload.php';
} else {
    echo "Error: Composer autoload not found.\n";
    exit(1);
}

use SixShop\MakerBundle\Generator\MigrationGenerator;
use SixShop\MakerBundle\Generator\ModelGenerator;
use SixShop\MakerBundle\Generator\EntityGenerator;
use SixShop\MakerBundle\Generator\ControllerGenerator;
use SixShop\MakerBundle\Generator\ComposerGenerator;
use SixShop\MakerBundle\Generator\RouteUpdater;

echo "🧪 SixShop Maker Bundle - Comprehensive Test Suite\n";
echo "=" . str_repeat("=", 50) . "\n\n";

$testDir = sys_get_temp_dir() . '/sixshop_test_' . time();
$passed = 0;
$failed = 0;

function test(string $name, callable $test): void
{
    global $passed, $failed;
    echo "📋 Testing: {$name}... ";
    
    try {
        $result = $test();
        if ($result) {
            echo "✅ PASSED\n";
            $passed++;
        } else {
            echo "❌ FAILED\n";
            $failed++;
        }
    } catch (Exception $e) {
        echo "💥 ERROR: " . $e->getMessage() . "\n";
        $failed++;
    }
}

function setupTestDir(): string
{
    global $testDir;
    if (!is_dir($testDir)) {
        mkdir($testDir, 0755, true);
    }
    return $testDir;
}

function cleanupTestDir(): void
{
    global $testDir;
    if (is_dir($testDir)) {
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($testDir, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );
        
        foreach ($iterator as $file) {
            if ($file->isDir()) {
                rmdir($file->getRealPath());
            } else {
                unlink($file->getRealPath());
            }
        }
        rmdir($testDir);
    }
}

// Test 1: MigrationGenerator
test("MigrationGenerator - Create Table", function() {
    $testDir = setupTestDir();
    $generator = new MigrationGenerator($testDir . '/migrations');
    
    $fields = [
        ['name' => 'id', 'type' => 'biginteger', 'null' => false],
        ['name' => 'name', 'type' => 'string', 'length' => 100, 'null' => false],
        ['name' => 'email', 'type' => 'string', 'length' => 255, 'null' => false, 'unique' => true]
    ];
    
    $result = $generator->generateMigration('users', $fields, 'create');
    
    // Check if file was created
    $files = glob($testDir . '/migrations/*_create_users_table.php');
    return $result && count($files) === 1;
});

test("MigrationGenerator - Add Column", function() {
    $testDir = setupTestDir();
    $generator = new MigrationGenerator($testDir . '/migrations');
    
    $fields = [
        ['name' => 'phone', 'type' => 'string', 'length' => 20, 'null' => true]
    ];
    
    $result = $generator->generateMigration('users', $fields, 'add_column');
    
    $files = glob($testDir . '/migrations/*_add_column_to_users_table.php');
    return $result && count($files) === 1;
});

test("MigrationGenerator - Drop Column", function() {
    $testDir = setupTestDir();
    $generator = new MigrationGenerator($testDir . '/migrations');
    
    $fields = [
        ['name' => 'deprecated_field']
    ];
    
    $result = $generator->generateMigration('users', $fields, 'drop_column');
    
    $files = glob($testDir . '/migrations/*_drop_column_from_users_table.php');
    return $result && count($files) === 1;
});

// Test 2: ComposerGenerator
test("ComposerGenerator - Package Name Validation", function() {
    $generator = new ComposerGenerator();
    
    $validNames = ['vendor/package', 'sixshop/hello-world'];
    $invalidNames = ['invalid', 'vendor/', '/package'];
    
    foreach ($validNames as $name) {
        if (!$generator->validatePackageName($name)) {
            return false;
        }
    }
    
    foreach ($invalidNames as $name) {
        if ($generator->validatePackageName($name)) {
            return false;
        }
    }
    
    return true;
});

test("ComposerGenerator - Namespace Conversion", function() {
    $generator = new ComposerGenerator();
    
    $testCases = [
        'sixshop/hello-world' => 'SixShop\\HelloWorld\\',
        'vendor/simple' => 'Vendor\\Simple\\',
        'my-vendor/complex-name' => 'MyVendor\\ComplexName\\'
    ];
    
    foreach ($testCases as $package => $expected) {
        $result = $generator->convertPackageNameToNamespace($package);
        if ($result !== $expected) {
            return false;
        }
    }
    
    return true;
});

test("ComposerGenerator - Generate composer.json", function() {
    $testDir = setupTestDir();
    $generator = new ComposerGenerator();
    
    $packageInfo = [
        'packageName' => 'sixshop/test-extension',
        'description' => 'A test extension',
        'namespace' => 'SixShop\\TestExtension\\',
        'id' => 'sixshop-test-extension'
    ];
    
    $result = $generator->generateComposerJson($packageInfo, $testDir);
    
    return $result && file_exists($testDir . '/composer.json');
});

// Test 3: ModelGenerator
test("ModelGenerator - Generate Model", function() {
    $testDir = setupTestDir();
    $generator = new ModelGenerator();
    
    $fields = [
        ['name' => 'id', 'type' => 'biginteger'],
        ['name' => 'name', 'type' => 'string', 'length' => 100],
        ['name' => 'price', 'type' => 'decimal', 'precision' => 10, 'scale' => 2]
    ];
    
    $extensionInfo = [
        'namespace' => 'SixShop\\Test\\',
        'packageName' => 'sixshop/test',
        'id' => 'sixshop-test'
    ];
    
    $result = $generator->generateModel('products', 'Products table', $fields, $extensionInfo, $testDir);
    
    return $result && file_exists($testDir . '/src/Model/ProductModel.php');
});

// Test 4: EntityGenerator  
test("EntityGenerator - Generate Entity", function() {
    $testDir = setupTestDir();
    $generator = new EntityGenerator();
    
    $fields = [
        ['name' => 'id', 'type' => 'biginteger'],
        ['name' => 'name', 'type' => 'string']
    ];
    
    $extensionInfo = [
        'namespace' => 'SixShop\\Test\\',
        'packageName' => 'sixshop/test',
        'id' => 'sixshop-test'
    ];
    
    $result = $generator->generateEntity('products', 'Products table', $fields, $extensionInfo, $testDir);
    
    return $result && file_exists($testDir . '/src/Entity/ProductEntity.php');
});

// Test 5: ControllerGenerator
test("ControllerGenerator - Generate Controllers", function() {
    $testDir = setupTestDir();
    $generator = new ControllerGenerator();
    
    $fields = [
        ['name' => 'id', 'type' => 'biginteger'],
        ['name' => 'name', 'type' => 'string']
    ];
    
    $extensionInfo = [
        'namespace' => 'SixShop\\Test\\',
        'packageName' => 'sixshop/test',
        'id' => 'sixshop-test'
    ];
    
    $result = $generator->generateControllers('products', 'Products table', $fields, $extensionInfo, $testDir);
    
    $adminExists = file_exists($testDir . '/src/Controller/Admin/ProductController.php');
    $apiExists = file_exists($testDir . '/src/Controller/Api/ProductController.php');
    
    return $result && $adminExists && $apiExists;
});

// Test 6: Complete Workflow
test("Complete Workflow - All Components", function() {
    $testDir = setupTestDir();
    
    $tableName = 'orders';
    $tableComment = 'Orders management';
    $fields = [
        ['name' => 'id', 'type' => 'biginteger', 'null' => false],
        ['name' => 'user_id', 'type' => 'biginteger', 'null' => false],
        ['name' => 'total', 'type' => 'decimal', 'precision' => 10, 'scale' => 2],
        ['name' => 'status', 'type' => 'string', 'length' => 20, 'default' => 'pending']
    ];
    
    $extensionInfo = [
        'namespace' => 'SixShop\\Shop\\',
        'packageName' => 'sixshop/shop',
        'id' => 'sixshop-shop'
    ];
    
    // Generate migration
    $migrationGenerator = new MigrationGenerator($testDir . '/database/migrations');
    $migrationResult = $migrationGenerator->generateMigration($tableName, $fields, 'create');
    
    // Generate model
    $modelGenerator = new ModelGenerator();
    $modelResult = $modelGenerator->generateModel($tableName, $tableComment, $fields, $extensionInfo, $testDir);
    
    // Generate entity
    $entityGenerator = new EntityGenerator();
    $entityResult = $entityGenerator->generateEntity($tableName, $tableComment, $fields, $extensionInfo, $testDir);
    
    // Generate controllers
    $controllerGenerator = new ControllerGenerator();
    $controllerResult = $controllerGenerator->generateControllers($tableName, $tableComment, $fields, $extensionInfo, $testDir);
    
    // Verify all files exist
    $migrationExists = !empty(glob($testDir . '/database/migrations/*_create_orders_table.php'));
    $modelExists = file_exists($testDir . '/src/Model/OrderModel.php');
    $entityExists = file_exists($testDir . '/src/Entity/OrderEntity.php');
    $adminControllerExists = file_exists($testDir . '/src/Controller/Admin/OrderController.php');
    $apiControllerExists = file_exists($testDir . '/src/Controller/Api/OrderController.php');
    
    return $migrationResult && $modelResult && $entityResult && $controllerResult &&
           $migrationExists && $modelExists && $entityExists && $adminControllerExists && $apiControllerExists;
});

// Test 7: Field Type Handling
test("Field Type Support", function() {
    $generator = new MigrationGenerator();
    $supportedTypes = $generator->getSupportedFieldTypes();
    
    $expectedTypes = [
        'integer', 'biginteger', 'string', 'text', 'boolean',
        'decimal', 'float', 'datetime', 'timestamp', 'date',
        'time', 'binary', 'json'
    ];
    
    foreach ($expectedTypes as $type) {
        if (!in_array($type, $supportedTypes)) {
            return false;
        }
    }
    
    return true;
});

// Test 8: Template Content Validation
test("Template Content Quality", function() {
    $testDir = setupTestDir();
    
    // Generate complete set
    $generator = new ModelGenerator();
    $extensionInfo = [
        'namespace' => 'SixShop\\Test\\',
        'packageName' => 'sixshop/test',
        'id' => 'sixshop-test'
    ];
    
    $fields = [
        ['name' => 'name', 'type' => 'string', 'length' => 100]
    ];
    
    $generator->generateModel('items', 'Test items', $fields, $extensionInfo, $testDir);
    
    $content = file_get_contents($testDir . '/src/Model/ItemModel.php');
    
    // Check for required elements
    $checks = [
        'class ItemModel extends Model',
        'protected function getOptions(): array',
        "'name' => 'items'",
        "'pk' => 'id'",
        "'auto_timestamp' => true"
    ];
    
    foreach ($checks as $check) {
        if (strpos($content, $check) === false) {
            return false;
        }
    }
    
    return true;
});

echo "\n" . str_repeat("=", 60) . "\n";
echo "📊 Test Results Summary\n";
echo str_repeat("=", 60) . "\n";
echo "✅ Passed: {$passed}\n";
echo "❌ Failed: {$failed}\n";
echo "📈 Success Rate: " . round(($passed / ($passed + $failed)) * 100, 1) . "%\n";

if ($failed === 0) {
    echo "\n🎉 All tests passed! The SixShop Maker Bundle is working correctly.\n";
} else {
    echo "\n⚠️  Some tests failed. Please review the output above.\n";
}

echo "\n💡 To run manual tests:\n";
echo "- Extension generation: php bin/sixshop-maker\n";
echo "- Migration generation: php bin/sixshop-maker create_migration\n";
echo "- Comprehensive demo: php test/comprehensive_demo.php\n";

// Cleanup
cleanupTestDir();

echo "\n🧹 Cleanup completed.\n";